var express = require('express');
var router = express.Router();
var {usermodel}=require('../database/models/userModel.js')
var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10);
// token
// 引入
var jwt = require('jsonwebtoken');
// 定义密钥
var secret="djhdhshdsjfsjmdhwvgskjddefds"


router.post('/', (req, res)=>{//注册
  console.log(req.body);
  let { phone, pwd } = req.body
  usermodel.find({ phone }).then(result => {
    // console.log(result);
    if (result.length != 0) {
      res.send({
        code: 110,
        msg:'手机号已注册，可直接登录'
      })
      return
    }
    // 密码加密
    var hash = bcrypt.hashSync(pwd, salt);
    console.log(hash);
    new usermodel({
      phone,
      hash
    }).save().then(result => {
      console.log(result);
      res.send({
        code: 111,
        msg:"注册成功"
      })
    })

  })
});
router.get('/', (req, res) => {
  console.log(req.query);
  let { phone, pwd } = req.query
  usermodel.find({ phone }).then(result => {
    if (result.length == 0) {//账号不存在
      res.send({
        code: 110,
        msg:'账号不存在，请注册'
      })
      return
    }
    // 如果账号存在，对比明文密码和加密密码
    let { hash } = result[0]
    let bool = bcrypt.compareSync(pwd, hash);//密码对比，返回bool值
    if (!bool) {
      res.send({
        code: 112,
        msg:'密码错误，请重试'
      })
      return
    }
    let userInfo = result[0]
    userInfo.hash = ''//不管是明文密码还是加密密码，都不应该下发密码
    // 签发token
    let token = jwt.sign({
      time: Date.now(),
      limit: 60*60 * 1000//有效性
    }, secret, (err, token) => {
      // 将token下发给前端
      let{phone,_id,avator}=userInfo
      res.send({
      code: 111,
      msg:'登录成功',
      data: {
        phone,
        _id,
        avator,
        token
      }
    })
    });
    
  })
})
module.exports = router;
